package com.rgs.pay.yisheng.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Random;
import java.util.Set;

/**
 * @program: com-rgs-parent
 * @description:
 * @author: Mr.Ren
 * @create: 2022-12-02 11:15
 **/
public class BasePayUtil {
    public static final String MER_RSA_PUBLIC_KEY =
            "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDksX6WM7EeaSoNJaQ2/K8IZibmjdOpfqPcH+RbyhaBghrdMjJr/zlKrIhc7mrWe1Vdocf1mrzlVbmzK+mFw/PxiDUrQv+h4+4od9Fw40CzNU0ZgX4bsfhTtyxGFFCym6fy2c/rVw1OkDeh78NwhjUYcHQFeUqtXdERIO7Wz7gmaQIDAQAB";

    /**
     * 易生支付提供的机构公钥  -- 联调支持提供或者文档上拷贝
     */
    public static final String EASYPAY_PUBLIC_KEY =
            "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCAqRw0nZ1rGTpAeKupP7coS+en6BveJL4aFVt9men4Zzkpuv/IeK6YJ2yk4m8ppZ7TLW4t5WsPEhYOnUfMtjhW4nuQfjgU54juJ1KMHYiX9gaaO+z80ZnaiKD2YsZMFiE9dlTeBlkRL5xXbHa+JonHfVKXMr13oI8oZNKdpnvknQIDAQAB";
    /**
     * 默认的接口签名方式
     */
    public static final String SIGN_TYPE_RSA256 = "RSA2";
    public static final String SIGN_TYPE_RSA = "RSA";
    /**
     * 接口返回成功代码
     */
    public static final String RET_CODE_SUCCESS = "000000";


    /**
     * 排序拼接需要签名的数据， ！！参数值不为空且trim不为空。
     *
     * @param dataObj 数据对象 不能都为空
     * @return 签名排序字符串
     */
    public static String getReqStr(Object dataObj) {
        JSONObject data = (JSONObject) JSON.toJSON(dataObj);
        Set<String> keySet = data.keySet();
        String[] keyArray = keySet.toArray(new String[keySet.size()]);
        Arrays.sort(keyArray);
        StringBuilder sb = new StringBuilder();
        for (String k : keyArray) {
            // 参数值为空，则不参与签名
            if (data.get(k) != null && data.get(k).toString().trim().length() > 0) {
                sb.append(k).append("=").append(data.get(k).toString().trim()).append("&");
            }
        }
        return sb.substring(0, sb.toString().lastIndexOf("&"));
    }

    /**
     * 验证易生返回的报文数据. !!!使用data字段的内容验签
     *
     * @param response 易生返回的数据
     * @return 验签是否成功
     */
    public static boolean checkSign(String response) {
        JSONObject json = JSON.parseObject(response);
        // 云易收sysRetCode 和 微收单 sysRetcode
        if ("000000".equals(json.getString("sysRetcode")) || "000000".equals(json.getString("sysRetCode"))) {
            String sign = json.getString("sign");
            if (StringUtils.isEmpty(sign)) {
                System.out.println("=====> 签名失败，该报文未返回签名数据");
                return false;
            }
            JSONObject jsonData = json.getJSONObject("data");
            boolean ret = RsaUtil.verifyBySHA256WithRSA(getReqStr(jsonData), sign, EASYPAY_PUBLIC_KEY);

            if (ret) {
                System.out.println("=====> 验签成功，接口数据安全");
                return true;
            } else {
                System.out.println("=====> 验签失败，请注意报文安全");
                return false;
            }
        } else {
            System.out.println("=====> 非00状态码，不需要验签");

            return false;
        }
    }

    public static boolean checkBizSign(String response) {
        JSONObject json = JSON.parseObject(response);
        // 云易收sysRetCode 和 微收单 sysRetcode
        if ("000000".equals(json.getString("sysRetcode")) || "000000".equals(json.getString("sysRetCode"))) {
            String sign = json.getString("sign");
            if (StringUtils.isEmpty(sign)) {
                System.out.println("=====> 签名失败，该报文未返回签名数据");
                return false;
            }
            JSONObject jsonData = json.getJSONObject("bizData");
            boolean ret = RsaUtil.verifyBySHA256WithRSA(getReqStr(jsonData), sign, EASYPAY_PUBLIC_KEY);

            if (ret) {
                System.out.println("=====> 验签成功，接口数据安全");
                return true;
            } else {
                System.out.println("=====> 验签失败，请注意报文安全");
                return false;
            }
        } else {
            System.out.println("=====> 非00状态码，不需要验签");

            return false;
        }
    }

    /**
     * 使用商户的私钥进行加签
     *
     * @param data: 签名数据，注意这里仅仅是文档中data字段的内容
     * @return java.lang.String 签名
     */
    public static String sign(Object data, String signKey) {
        String reqStr = getReqStr(data);

        String res = RsaUtil.signBySHA256WithRSA(reqStr, signKey);


//        System.out.println("\n==========================================================签名过程 开始==========================================================" + "\n【签名KEY：】" + MER_RSA_PRIVATE_KEY + "\n\n【原始数据：】" + data + "\n【真正签名的数据：】" + reqStr + "\n【签名后的值：】" + res + "\n==========================================================签名过程 结束==========================================================\n");

        return res;
    }

    /**
     * 自动生成订单号
     *
     * @return
     */
    public static String getTradeNoByTime() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String newDate = sdf.format(new Date());
        String result = "";
        Random random = new Random();
        for (int i = 0; i < 3; i++) {
            result += random.nextInt(10);
        }
        return newDate + result;
    }


}

